import { generateUniqueId } from "utils/utils";


export class TimerManager 
{
    // 定时器 触发事件
    private _timer!:ITimer[];
    emitter!:TEventEmitter<TEventTypes>
    constructor()
    {
        if(!this._timer)
        {
            this._timer=[]
        }
    }

    public register<T extends TimerArg<TEventTypes>>(event:T,ttl:number,interval=1)
    {
        const timer:ITimer<T>={
            id:generateUniqueId(),
            interval:interval,
            ttl:ttl,
            event:event
        }
        this._timer.push(timer);
        return timer;
    }


    public remove(timerid:string)
    {
        let index = this._timer.findIndex(e=>e.id == timerid);
        if(index>-1)
        {
            this._timer.splice(index,1);
        }
    }


    public tick()
    {
         
        for(let i=0;i<this._timer.length;)
        {
            const e = this._timer[i];
            if(Game.time%e.interval ==0)
            {
                this.emitter(e.event.region,e.event.type,e.event);
            }
            
            if(e.ttl>0)
            {
                e.ttl--
            }else if(e.ttl == 0)
            {
                this._timer.splice(i,1);
                continue;
            }
            else 
            {

            }
            i++;
        }
         
    }
}